﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Npgsql;

namespace Thesis_v01
{
   public partial class Login : Form
   {
      private MainApp mainWindow;

      public Login(MainApp mainWin)
      {
         InitializeComponent();

         mainWindow = mainWin;
      }

      private void exitButton_Click(object sender, EventArgs e)
      {
         this.Close();
         mainWindow.IsLoggedIn = false;
         mainWindow.ToggleLogin();
         //mainWindow.Close();
      }

      private void loginButton_Click(object sender, EventArgs e)
      {
         DBConnection dbConn = new DBConnection();
         LoginDetail login = dbConn.AttemptLogin(usernameTextBox.Text, passwordTextBox.Text);

         if (login != null)
         {
            try
            {
               mainWindow.InstructorID = login.UserID;
               mainWindow.IsLoggedIn = login.Success;
               mainWindow.ToggleLogin();

               if (mainWindow.IsLoggedIn)
               {
                  this.Close();
               }
               else
               {
                  MessageBox.Show(login.Description, "Login status");
               }
            }
            catch (Exception error)
            {
               MessageBox.Show(error.ToString());
            }
         }
      }

      private void usernameTextBox_TextChanged(object sender, EventArgs e)
      {
         if (usernameTextBox.Text != "")
         {
            passwordTextBox.Enabled = true;
         }
         else
         {
            passwordTextBox.Enabled = false;
         }
      }

      private void Form1_FormClosing(object sender, FormClosingEventArgs e)
      {
         /*if (!mainWindow.IsLoggedIn)
         {
            // Display a MsgBox asking the user to save changes or abort.
            if (MessageBox.Show("Are you sure you want to cancel login?", "Confirm close",
               MessageBoxButtons.YesNo) == DialogResult.No)
            {
               // Cancel the Closing event from closing the form.
               e.Cancel = true;
               // Call method to save file...
            }
            else
            {
               mainWindow.Close();
            }
         }*/
      }

      private void Login_Load(object sender, EventArgs e)
      {
         usernameTextBox.Focus();
      }

   }
}
